#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <pthread.h>
#include <arpa/inet.h>

#define PORT 8080
#define SERVER_IP "127.0.0.1"

void *connection_handler(void *);

int main() {
    int sockfd;
    struct sockaddr_in serv_addr;
    pthread_t thread_id;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("ERROR opening socket");
        exit(1);
    }

    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    serv_addr.sin_port = htons(PORT);

    if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
        perror("ERROR connecting");
        exit(1);
    }

    if (pthread_create(&thread_id, NULL, connection_handler, (void*) &sockfd) < 0) {
        perror("ERROR on thread creation");
        return 1;
    }

    pthread_join(thread_id, NULL);

    close(sockfd);
    return 0;
}

void *connection_handler(void *socket_desc) {
    int sock = *(int*)socket_desc;
    char buffer[256];

    while (1) {
        printf("Please enter the message:");
        bzero(buffer, 256);
        fgets(buffer, 255, stdin);

        write(sock, buffer, strlen(buffer));

        if (strcmp(buffer, "exit\n") == 0) {
            break;
        }
    }
    return 0;
}
